#ifndef __DALELIB_FLIPBOOK_H__
#define __DALELIB_FLIPBOOK_H__

#include <dalelib/maths.h>

#include <fstream>
#include <map>
#include <vector>
#include <string>
using namespace std;



namespace dalelib
{

class FlipBook
{
private:

	struct Frame
	{
		float _delay;
		v2 _tmin, _tmax;

		Frame() { }

		Frame(float _Delay,v2 _TMin,v2 _TMax)
			: _delay(_Delay)
			, _tmin(_TMin)
			, _tmax(_TMax)
		{ }
	};

	map<string,int> _anim_names;
	typedef vector<Frame> Anim;
	typedef vector<Anim> AnimList;
	AnimList _anims;

	float _time;

public:

	FlipBook() { }

	FlipBook(const string _FileName) { load(_FileName); }

	void load(const string _FileName)
	{
		string str;
		ifstream fin( _FileName.c_str() );
		if( !fin ) { cout << "can't load flipbook file: " << _FileName << endl; return; }

		Anim* current_anim = 0;

		int brackets = 0;
		do
		{
			fin >> str;

			if( !str.compare("{") ) { ++brackets; }

			if( !str.compare("}") ) { --brackets; }

			if( !str.compare("FRAME") )
			{
				Frame f;
				fin >> f._delay >> f._tmin[0] >> f._tmin[1] >> f._tmax[0] >> f._tmax[1];
				if(current_anim) current_anim->push_back(f);
			}

			if( !str.compare("ANIM") )
			{
				string name;
				fin >> name;
				_anim_names[name] = _anims.size();
				_anims.push_back(Anim());
				current_anim = &_anims[_anim_names[name]];
			}

		} while( !fin.eof() );

		fin.close();
	}

	void animate(const int _AnimIndex, float &_AnimTime, v2 &_Tmin, v2 &_Tmax,const float _SpeedModifier=1.f)
	{
		if( _AnimIndex<_anims.size() )
		{
			int frame = int(floor(_AnimTime));
			if( frame<_anims[_AnimIndex].size() )
			{
				_AnimTime += _anims[_AnimIndex][frame]._delay*_SpeedModifier;
				if( _AnimTime>=_anims[_AnimIndex].size() )
				{
                    _AnimTime -= float(_anims[_AnimIndex].size());
				}
				_Tmin = _anims[_AnimIndex][frame]._tmin;
				_Tmax = _anims[_AnimIndex][frame]._tmax;
			}
		}
	}

	int getAnimIndexFromName(const string _AnimName) { return _anim_names[_AnimName]; }

	void dump()
	{
		cout << "Flipbook:" << endl;
		for(int i=0; i<_anims.size(); ++i)
		{
			cout << "    Anim: " << endl;
			for(int j=0; j<_anims[i].size(); ++j)
			{
				cout << "        delay: " << _anims[i][j]._delay;
				cout << "   tmin: " << _anims[i][j]._tmin[0] << " " << _anims[i][j]._tmin[0];
				cout << "   tmax: " << _anims[i][j]._tmax[0] << " " << _anims[i][j]._tmax[0] << endl;
			}
		}
	}

};

} // namespace dalelib

#endif
